from django.shortcuts import render, HttpResponse
from .forms import MessageBoardForm, RegisterForm
# 请求验证装饰器
from django.views.decorators.http import require_http_methods

# Create your views here.

# 请求的method
# 1.GET 是用来从服务器上获取数据
# 2.POST 是用来向服务器提交数据的

@require_http_methods(['GET', 'POST'])  # 限制它只能使用get请求或者post请求
def index(request):
    # 如果用GET请求，那么就返回一个页面
    if request.method == 'GET':
        form = MessageBoardForm()
        return render(request, "index.html", context={'form': form})
    else:
        # 对用post请求提交上来的数据，用表单验证是否满足请求
        form = MessageBoardForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')   # cleaned_data 表示经过表单验证过的数据
            content = form.cleaned_data.get('content')
            email = form.cleaned_data.get('email')
            return HttpResponse(f'{title}, {content}, {email}')
        else:
            print(form.errors)
            return HttpResponse("表单验证失败")

# 视图函数
@require_http_methods(['GET','POST'])
def register_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            return HttpResponse(telephone)
        else:
            print(form.errors.get_json_data())
            return HttpResponse('表单验证失败')



